package com.test.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;


public class JdbcUtils {

    private static DruidDataSource dataSource;


    static {
        Properties properties=new Properties();
        //读取配置文件
        InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");

        try {
            properties.load(resourceAsStream);
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
            System.out.println("dataSource = " + dataSource.getConnection());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){

    }

    /**
     * 返回null失败，否则成功
     * @return
     */
    public static Connection getConnection(){
        Connection connection=null;
        try {
            connection=dataSource.getConnection();
        } catch (SQLException e) {
                   e.printStackTrace();
        }
        return connection;
    }


    public static void close(Connection connection){
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
